﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Drawing;

namespace RayTracer
{
    static class NetXmlExtensions
    {
        #region Color
        /// <summary>
        /// Wandelt die Farbe in einen XML-Knoten.
        /// </summary>
        /// <param name="color">Die Farbe.</param>
        /// <param name="xmlDocument">Das zugrunde liegende XML-Dokument.</param>
        /// <param name="name">Der Name des Knotens.</param>
        /// <returns>Der XML-Knoten.</returns>
        internal static XmlNode ToXml(this Color color, XmlDocument xmlDocument, string name)
        {
            XmlNode node = xmlDocument.CreateNode(XmlNodeType.Element, name, null);
            XmlAttribute attributeA = xmlDocument.CreateAttribute("a");
            XmlAttribute attributeR = xmlDocument.CreateAttribute("r");
            XmlAttribute attributeG = xmlDocument.CreateAttribute("g");
            XmlAttribute attributeB = xmlDocument.CreateAttribute("b");
            attributeA.InnerText = color.A.ToString();
            attributeR.InnerText = color.R.ToString();
            attributeG.InnerText = color.G.ToString();
            attributeB.InnerText = color.B.ToString();
            node.Attributes.Append(attributeA);
            node.Attributes.Append(attributeR);
            node.Attributes.Append(attributeG);
            node.Attributes.Append(attributeB);
            return node;
        }

        /// <summary>
        /// Weist der Farbe die Werte aus dem XML-Knoten zu.
        /// </summary>
        /// <param name="xmlNode">Der XML-Knoten.</param>
        /// <returns>Die Farbe.</returns>
        internal static Color ColorFromXml(XmlNode xmlNode)
        {
            XmlNode attributeA = xmlNode.Attributes.GetNamedItem("a");
            XmlNode attributeR = xmlNode.Attributes.GetNamedItem("r");
            XmlNode attributeG = xmlNode.Attributes.GetNamedItem("g");
            XmlNode attributeB = xmlNode.Attributes.GetNamedItem("b");
            byte a = 0, r = 0, g = 0, b = 0;
           if (attributeA != null) byte.TryParse(attributeA.InnerText, out a);
           if (attributeR != null) byte.TryParse(attributeR.InnerText, out r);
           if (attributeG != null) byte.TryParse(attributeG.InnerText, out g);
           if (attributeB != null) byte.TryParse(attributeB.InnerText, out b);
           return Color.FromArgb((int)a,(int)r,(int)g,(int)b);
        }
        #endregion Color
    }
}
